package network;

import java.awt.Shape;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import javax.swing.SwingUtilities;

import org.jhotdraw.draw.Figure;
import org.joda.time.DateTime;

import master.ChildInterface;

import sr.logger.Logger;
import views.GameWindow;
import views.MainWindow;

import client.remote.ClientReceiver;


public class ReceiverImpl extends UnicastRemoteObject implements ClientReceiver
{
	Logger logger = Logger.getLogger(this.getClass());
	Object gui;
	private MainWindow mainWindow;
	private GameWindow gameWindow;
	protected ReceiverImpl() throws RemoteException {
		// TODO Auto-generated constructor stub
	}


	@Override
	public void addMessage(final String msg,Long tick) throws RemoteException 
	{
		logger.log(tick, "addMessage");
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() 
			{
				mainWindow.addChatMessage(msg);
			}
		});
	}

	@Override
	public void informAboutGameStart(final int timeTillNextGame,Long tick)
			throws RemoteException 
	{
		logger.log(tick, "infoAboutGameStart");
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				mainWindow.addChatMessage("You will join game in: " + timeTillNextGame + "ms");
			}
		});
	}
	@Override
	public void startGame(final ChildInterface childInterface,Long tick) throws RemoteException 
	{
		logger.log(tick, "startGame");
		SwingUtilities.invokeLater(new Runnable()
		{
			
			@Override
			public void run()
			{
				mainWindow.startGame();
				
			}
		});
		MasterCommunicator.getMasterCommunicator().setChildRef(childInterface);
	}

	@Override
	public void addRoomMessage(final String msg,Long tick) throws RemoteException {
		
		logger.log(tick, "addRoomMessage");
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				gameWindow.addChatMessage(msg);
			}
		});
		
	}


	public void setMainWindowRef(MainWindow mainWindow) {
		this.mainWindow = mainWindow;
		
	}


	public void setGameWindowRef(GameWindow gameWindow)
	{
		this.gameWindow = gameWindow;
		
	}


	@Override
	public void addFigure(final Shape shape,Long tick) throws RemoteException
	{
		logger.log(tick, "addFigure");
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("client draw figure at: " + DateTime.now().millisOfDay().get());
				gameWindow.addFigure(shape);
			}
			
		});
		
	}


	@Override
	public void changeServer(ChildInterface childInterface,Long tick)
			throws RemoteException
	{
		logger.log(tick, "changeServer");
		MasterCommunicator.getMasterCommunicator().setChildRef(childInterface);
		
	}

}
